require "import"
import "android.net.Uri"
import "java.lang.Thread"

local url = "https://www.bbc.com/arabic"
local numberOfTitles = 10
local delay = 5000

local newsTitles = {}

function displayNews(index)
  local currentNews = newsTitles[index]
  service.speak(currentNews)
  print(currentNews) -- يعرض الخبر كاملاً على الشاشة
end

function onNextButtonClicked(index)
  index = index + 1
  if index <= #newsTitles then
    displayNews(index)
  end
end

function onPreviousButtonClicked(index)
  index = index - 1
  if index >= 1 then
    displayNews(index)
  end
end

Http.get(url, function(status, data)
    if status == 200 then
        io.open("/storage/emulated/0/Download/html_data.txt", "w"):write(data):close()
        for title in string.gmatch(data, "<h3[^>]->(.-)</h3>") do
            local cleanedTitle = string.gsub(title, "<[^>]+>", "")
            table.insert(newsTitles, cleanedTitle)
        end
        local titleCount = math.min(numberOfTitles, #newsTitles)
        local currentIndex = 1
        displayNews(currentIndex)

        while currentIndex < titleCount do
            Thread.sleep(delay)
            onNextButtonClicked(currentIndex)
            currentIndex = currentIndex + 1
        end
    else
        service.speak("لم يتم العثور على الصفحة")
    end
end)